package org.activemonitoring.datastore.rest.client;

import javax.ws.rs.core.MediaType;

import org.activemonitoring.datastore.DataStore;
import org.activemonitoring.domain.Measures;
import org.apache.commons.lang.Validate;
import org.springframework.stereotype.Component;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

@Component
public class DataStoreRestClient implements DataStore {

    private Client client;
    private WebResource resource;
    private String datastoreUrl;

    public DataStoreRestClient() throws Exception {
        super();
        DefaultClientConfig clientConfig = new DefaultClientConfig();
        clientConfig.getClasses().add(MeasuresWriter.class);
        this.client = createClient(clientConfig);
    }

    protected Client createClient(ClientConfig clientConfig) {
        return Client.create(clientConfig);
    }

    @Override
    public void store(Measures measures) {
        Validate.notNull(this.resource, "You should specify the REST url of the datastore");
        // Get the current properties and verify it is empty
        this.resource.accept(MediaType.TEXT_XML_TYPE).entity(measures, MediaType.TEXT_XML_TYPE).post();
    }

    public boolean ping() {
        String pingUrl = this.datastoreUrl + "/ping";
        System.out.println(pingUrl);
        String pingResult = this.client.resource(pingUrl).accept(MediaType.TEXT_PLAIN_TYPE).get(String.class);
        return "pinged!".equals(pingResult);
    }

    public void setDatastoreUrl(String datastoreUrl) {
        this.datastoreUrl = datastoreUrl;
        this.resource = this.client.resource(this.datastoreUrl);
    }
}
